<template>
  <div class="users-management">
    <div class="page-header">
      <h2>教师用户授权管理</h2>
      <el-button type="primary" @click="showCreateTeacherDialog">
        <el-icon><el-icon-plus /></el-icon>添加教师用户
      </el-button>
    </div>

    <!-- 用户列表 -->
    <el-card class="user-list-card">
      <el-table :data="teachers" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户账号" />
        <el-table-column prop="realName" label="教师姓名" />
        <el-table-column prop="email" label="电子邮箱" />
        <el-table-column prop="department" label="所属院系" />
        <el-table-column prop="createdAt" label="注册日期" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="confirmDeleteUser(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        layout="total, prev, pager, next"
        :total="totalTeachers"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 创建教师对话框 -->
    <el-dialog v-model="createTeacherDialogVisible" title="添加教师用户" width="500px">
      <el-form
        ref="createTeacherFormRef"
        :model="createTeacherForm"
        :rules="createTeacherRules"
        label-width="100px"
      >
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="createTeacherForm.username" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="教师姓名" prop="realName">
          <el-input v-model="createTeacherForm.realName" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="createTeacherForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input v-model="createTeacherForm.department" placeholder="请输入所属院系" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="createTeacherForm.password" placeholder="请设置登录密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="createTeacherForm.confirmPassword" placeholder="请再次输入密码" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createTeacherDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateTeacher" :loading="submitting">确认添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editUserDialogVisible" title="修改用户信息" width="500px">
      <el-form
        ref="editUserFormRef"
        :model="editUserForm"
        :rules="editUserRules"
        label-width="100px"
      >
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="editUserForm.username" placeholder="用户账号" disabled />
        </el-form-item>
        <el-form-item label="用户姓名" prop="realName">
          <el-input v-model="editUserForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editUserForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input v-model="editUserForm.department" placeholder="请输入所属院系" />
        </el-form-item>
        <el-form-item label="重置密码" prop="resetPassword">
          <el-switch v-model="editUserForm.resetPassword" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" v-if="editUserForm.resetPassword">
          <el-input v-model="editUserForm.newPassword" placeholder="请输入新密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmNewPassword" v-if="editUserForm.resetPassword">
          <el-input v-model="editUserForm.confirmNewPassword" placeholder="请再次输入新密码" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditUser" :loading="submitting">保存更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus as ElIconPlus } from '@element-plus/icons-vue'
import UserService from '../../api/user'

interface User {
  id: string
  username: string
  realName: string
  email: string
  department: string
  createdAt: string
}

export default defineComponent({
  name: 'UsersManagement',
  components: {
    ElIconPlus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 表格数据
    const loading = ref(false)
    const teachers = ref<User[]>([])
    const totalTeachers = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 创建教师表单
    const createTeacherDialogVisible = ref(false)
    const createTeacherFormRef = ref<FormInstance>()
    const createTeacherForm = reactive({
      username: '',
      realName: '',
      email: '',
      department: '',
      password: '',
      confirmPassword: ''
    })
    
    // 编辑用户表单
    const editUserDialogVisible = ref(false)
    const editUserFormRef = ref<FormInstance>()
    const editUserForm = reactive({
      id: '',
      username: '',
      realName: '',
      email: '',
      department: '',
      resetPassword: false,
      newPassword: '',
      confirmNewPassword: ''
    })
    
    const submitting = ref(false)
    
    // 表单验证规则
    const validatePassword = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6个字符'))
      } else {
        callback()
      }
    }
    
    const validateConfirmPassword = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== createTeacherForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    const validateEditConfirmPassword = (rule: any, value: string, callback: any) => {
      if (editUserForm.resetPassword) {
        if (value === '') {
          callback(new Error('请再次输入新密码'))
        } else if (value !== editUserForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    
    const createTeacherRules = reactive<FormRules>({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请输入部门', trigger: 'blur' }
      ],
      password: [
        { required: true, validator: validatePassword, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
      ]
    })
    
    const editUserRules = reactive<FormRules>({
      realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请输入部门', trigger: 'blur' }
      ],
      newPassword: [
        { 
          validator: (rule, value, callback) => {
            if (editUserForm.resetPassword && value === '') {
              callback(new Error('请输入新密码'))
            } else if (editUserForm.resetPassword && value.length < 6) {
              callback(new Error('密码长度不能少于6个字符'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      confirmNewPassword: [
        { validator: validateEditConfirmPassword, trigger: 'blur' }
      ]
    })
    
    // 加载用户数据
    const loadUsers = async () => {
      loading.value = true
      try {
        const response = await UserService.getAllTeachers()
        teachers.value = response.data
        totalTeachers.value = response.data.length
      } catch (error) {
        console.error('加载用户数据失败:', error)
        ElMessage.error('加载用户数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 显示创建教师对话框
    const showCreateTeacherDialog = () => {
      createTeacherDialogVisible.value = true
      // 重置表单
      Object.keys(createTeacherForm).forEach(key => {
        createTeacherForm[key as keyof typeof createTeacherForm] = ''
      })
      
      // 重置表单验证
      createTeacherFormRef.value?.resetFields()
    }
    
    // 提交创建教师表单
    const submitCreateTeacher = async () => {
      if (!createTeacherFormRef.value) return
      
      await createTeacherFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            // API调用创建教师账号
            await UserService.createTeacher({
              username: createTeacherForm.username,
              realName: createTeacherForm.realName,
              email: createTeacherForm.email,
              department: createTeacherForm.department,
              password: createTeacherForm.password
            })
            
            ElMessage.success('教师账号创建成功')
            createTeacherDialogVisible.value = false
            loadUsers() // 刷新教师列表
          } catch (error: any) {
            ElMessage.error(error.response?.data?.message || '创建教师账号失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 编辑用户
    const editUser = (user: any) => {
      editUserForm.id = user.id
      editUserForm.username = user.username
      editUserForm.realName = user.realName
      editUserForm.email = user.email
      editUserForm.department = user.department
      editUserForm.resetPassword = false
      editUserForm.newPassword = ''
      editUserForm.confirmNewPassword = ''
      
      editUserDialogVisible.value = true
      // 重置表单验证
      editUserFormRef.value?.resetFields()
    }
    
    // 提交编辑用户表单
    const submitEditUser = async () => {
      if (!editUserFormRef.value) return
      
      await editUserFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            // API调用更新用户信息
            const data: any = {
              id: editUserForm.id,
              realName: editUserForm.realName,
              email: editUserForm.email,
              department: editUserForm.department,
            }
            
            if (editUserForm.resetPassword) {
              data.newPassword = editUserForm.newPassword
            }
            
            await UserService.updateUser(data)
            
            ElMessage.success('用户信息更新成功')
            editUserDialogVisible.value = false
            loadUsers() // 刷新用户列表
          } catch (error: any) {
            ElMessage.error(error.response?.data?.message || '更新用户信息失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 确认删除用户
    const confirmDeleteUser = (user: any) => {
      ElMessageBox.confirm(
        `确定要删除用户 ${user.realName} (${user.username}) 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // API调用删除用户
          await UserService.deleteUser(user.id)
          ElMessage.success('用户删除成功')
          loadUsers() // 刷新用户列表
        } catch (error: any) {
          ElMessage.error(error.response?.data?.message || '删除用户失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 页码变化
    const handlePageChange = (page: number) => {
      currentPage.value = page
      loadUsers()
    }
    
    // 如果URL有查询参数action=create，自动打开创建教师对话框
    watch(() => route.query, (query) => {
      if (query.action === 'create') {
        // 移除query参数
        router.replace({ path: route.path })
        showCreateTeacherDialog()
      }
    }, { immediate: true })
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      loading,
      teachers,
      totalTeachers,
      currentPage,
      pageSize,
      createTeacherDialogVisible,
      createTeacherFormRef,
      createTeacherForm,
      createTeacherRules,
      editUserDialogVisible,
      editUserFormRef,
      editUserForm,
      editUserRules,
      submitting,
      showCreateTeacherDialog,
      submitCreateTeacher,
      editUser,
      submitEditUser,
      confirmDeleteUser,
      handlePageChange
    }
  }
})
</script>

<style lang="scss" scoped>
.users-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 22px;
    }
  }
  
  .user-list-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 